import React, { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate, Link } from 'react-router-dom';
import { request } from '@/api/request';
import visaicon from '@/assets/images/become/visa.png';
import wsd from '@/assets/images/become/wsd.png';
import perion2 from '@/assets/images/buyTokens/10.webp'
import { getDynamicFonts } from '@/utils/fontUtils';
import ptVip from '@/assets/images/ptVip.png'
import xyVip from '@/assets/images/xyVip.png'
import zzVip from '@/assets/images/zzVip.png'
import freeVip from '@/assets/images/freeVip.png'
import { useMessage } from '@/components/messageApi';
import useIsMobile from '@/hooks/isMoboile';
import deamo from '@/assets/images/deamo.webp';
import gem from '@/assets/images/gem.png'
import gems from '@/assets/images/gems.png'
import Moregem from '@/assets/images/moregems.png'
import { motion, AnimatePresence } from 'framer-motion';



// 价格配置类型定义
interface PriceConfigItem {
  stripe_price_id: string;
  name: string;
  price: string;
  membershipType: string;
  discount?: string;
  recommended?: boolean;
  nameKey?: string;
}

// 价格配置 正式
const PRICE_CONFIG: Record<string, PriceConfigItem> = {
  // 非会员
  free_1000: {
    stripe_price_id: "price_1RqwQDChGeSzAdpVTowSkZYP",
    name: "1,000 tokens", // 这个将被getTokenName动态替换
    price: "¥2,000",
    membershipType: "free"
  },
  free_5000: {
    stripe_price_id: "price_1RqwQaChGeSzAdpV8RGBXFpq",
    name: "5,000 tokens", // 这个将被getTokenName动态替换
    price: "¥10,000",
    membershipType: "free",
    discount: ""
  },
  // 会员一 (Prelude)
  prelude_1000: {
    stripe_price_id: "price_1RqwJqChGeSzAdpVvXbHwdvJ",
    name: "1,000 tokens", // 这个将被getTokenName动态替换
    price: "¥1,500",
    membershipType: "prelude",
    discount: "节省 ¥500",
  },
  prelude_5000: {
    stripe_price_id: "price_1RqwLNChGeSzAdpVcgAVHl8m",
    name: "5,000 tokens", // 这个将被getTokenName动态替换
    price: "¥7,500",
    membershipType: "prelude",
    discount: "节省 ¥2,500"
  },
  // 会员二 (Affinity) - 主力产品
  affinity_1000: {
    stripe_price_id: "price_1RqwLyChGeSzAdpVSYin2taA",
    name: "1,000 tokens", // 这个将被getTokenName动态替换
    price: "¥1,000",
    membershipType: "affinity",
    discount: "节省 ¥1,000",
  },
  affinity_5000: {
    stripe_price_id: "price_1RqwMWChGeSzAdpVMeaVR2tF",
    name: "5,000 tokens", // 这个将被getTokenName动态替换
    price: "¥5,000",
    membershipType: "affinity",
    discount: "节省 ¥5,000",
    recommended: false
  },
  // 会员三 (Soulmate)
  soulmate_1000: {
    stripe_price_id: "price_1RqwN1ChGeSzAdpVtIrexKbW",
    name: "1,000 tokens", // 这个将被getTokenName动态替换
    price: "¥800",
    membershipType: "soulmate",
    discount: "节省 ¥1,200",
  },
  soulmate_5000: {
    stripe_price_id: "price_1RqwNlChGeSzAdpVx9R7Qvwg",
    name: "5,000 tokens", // 这个将被getTokenName动态替换
    price: "¥4,000",
    membershipType: "soulmate",
    discount: "节省 ¥6,000",
    // recommended: true
  }
};

// 价格配置 测试
// const PRICE_CONFIG: Record<string, PriceConfigItem> = {
//   // 非会员
//   free_1000: {
//     stripe_price_id: "price_1RiRmxEHIcYxLscxOD8jLPkQ",
//     name: "1,000 tokens", // 这个将被getTokenName动态替换
//     price: "¥2,000",
//     membershipType: "free"
//   },
//   free_5000: {
//     stripe_price_id: "price_1RiRqmEHIcYxLscxndhy2TYK",
//     name: "5,000 tokens", // 这个将被getTokenName动态替换
//     price: "¥10,000",
//     membershipType: "free",
//     discount: ""
//   },
//   // 会员一 (Prelude)
//   prelude_1000: {
//     stripe_price_id: "price_1RiRgdEHIcYxLscxjW9Wj9RB",
//     name: "1,000 tokens", // 这个将被getTokenName动态替换
//     price: "¥1,500",
//     membershipType: "prelude"
//   },
//   prelude_5000: {
//     stripe_price_id: "price_1RiRhgEHIcYxLscxjxMbZzxY",
//     name: "5,000 tokens", // 这个将被getTokenName动态替换
//     price: "¥7,500",
//     membershipType: "prelude",
//     discount: "节省 ¥2,500"
//   },
//   // 会员二 (Affinity) - 主力产品
//   affinity_1000: {
//     stripe_price_id: "price_1RiRiHEHIcYxLscxJ4ze52dm",
//     name: "1,000 tokens", // 这个将被getTokenName动态替换
//     price: "¥1,000",
//     membershipType: "affinity"
//   },
//   affinity_5000: {
//     stripe_price_id: "price_1RiRjUEHIcYxLscxbkOCTze1",
//     name: "5,000 tokens", // 这个将被getTokenName动态替换
//     price: "¥5,000",
//     membershipType: "affinity",
//     discount: "节省 ¥5,000",
//     recommended: false
//   },
//   // 会员三 (Soulmate)
//   soulmate_1000: {
//     stripe_price_id: "price_1RiRkAEHIcYxLscxjKiBAgLJ",
//     name: "1,000 tokens", // 这个将被getTokenName动态替换
//     price: "¥800",
//     membershipType: "soulmate"
//   },
//   soulmate_5000: {
//     stripe_price_id: "price_1RiRl6EHIcYxLscxabjm1WuL",
//     name: "5,000 tokens", // 这个将被getTokenName动态替换
//     price: "¥4,000",
//     membershipType: "soulmate",
//     discount: "节省 ¥6,000",
//     // recommended: true
//   }
// };

// 会员类型配置接口
interface MembershipType {
  name: string;
  description: string;
  highlight: boolean;
  benefits: string[];
}

// 会员共享的基础功能
const COMMON_BENEFITS = [
  "无限对话",
  "高级AI功能",
  "图片生成",
  "语音对话",
  "无广告",
  "数据安全"
];

// 会员类型配置
const MEMBERSHIP_TYPES: Record<string, MembershipType> = {
  free: {
    name: "非会员",
    description: "基础功能",
    highlight: false,
    benefits: [
      ...COMMON_BENEFITS,
      "响应速度：标准"
    ]
  },
  prelude: {
    name: "Prelude",
    description: "入门会员",
    highlight: false,
    benefits: [
      ...COMMON_BENEFITS,
      "赠送 1,000 tokens",
      "响应速度：快"
    ]
  },
  affinity: {
    name: "Affinity",
    description: "推荐会员",
    highlight: true, // 高亮显示
    benefits: [
      ...COMMON_BENEFITS,
      "赠送 3,000 tokens",
      "响应速度：更快"
    ]
  },
  soulmate: {
    name: "Soulmate",
    description: "高级会员",
    highlight: false,
    benefits: [
      ...COMMON_BENEFITS,
      "赠送 9,000 tokens",
      "响应速度：最快"
    ]
  }
};

interface BuyTokenProps {
  className?: string;
}

const BuyToken: React.FC<BuyTokenProps> = ({ className = '' }) => {
  const { t, i18n } = useTranslation();
  const dynamicFonts = getDynamicFonts(i18n);
  const navigate = useNavigate();
  const messageApi = useMessage(); // 初始化消息API
  const [selectedPlan, setSelectedPlan] = useState(''); // 默认不选中任何计划
  const [isLoading, setIsLoading] = useState(false); // 支付loading状态
  const [hoveredCard, setHoveredCard] = useState<string | null>(null); // 鼠标悬停状态
  const isMobile = useIsMobile(); // 使用移动端检测hook

  // 获取用户数据和当前VIP等级
  const [userData, setUserData] = useState<any>(null);
  const [currentVipLevel, setCurrentVipLevel] = useState<number>(0);

  // VIP等级与套餐类型的映射
  const vipLevelToPlan: Record<number, string> = {
    1: 'prelude',
    2: 'affinity',
    3: 'soulmate'
  };

  // 创建引用来访问不同产品的容器元素
  const freeCardRef = React.useRef<HTMLDivElement>(null);
  const preludeCardRef = React.useRef<HTMLDivElement>(null);
  const affinityCardRef = React.useRef<HTMLDivElement>(null);
  const soulmateCardRef = React.useRef<HTMLDivElement>(null);

  // 在组件初始化时获取用户数据和等级
  useEffect(() => {
    // 获取用户数据
    const userDataString = localStorage.getItem('userData');
    if (userDataString) {
      const parsedUserData = JSON.parse(userDataString);
      setUserData(parsedUserData);

      // 获取当前VIP等级
      if (parsedUserData && parsedUserData.vip_live) {
        setCurrentVipLevel(parsedUserData.vip_live);
      }
    }
  }, []);

  // 添加自动滚动到用户可购买产品位置的效果
  useEffect(() => {
    // 在移动端，当组件挂载后，根据用户会员等级滚动到对应可购买的产品位置
    if (isMobile) {
      const timer = setTimeout(() => {
        let targetRef = null;

        // 根据用户会员等级确定滚动目标
        switch (currentVipLevel) {
          case 0: // 非会员，滚动到free产品
            targetRef = freeCardRef;
            break;
          case 1: // Prelude会员，滚动到prelude产品
            targetRef = preludeCardRef;
            break;
          case 2: // Affinity会员，滚动到affinity产品
            targetRef = affinityCardRef;
            break;
          case 3: // Soulmate会员，滚动到soulmate产品
            targetRef = soulmateCardRef;
            break;
          default:
            targetRef = freeCardRef; // 默认滚动到free产品
        }

        // 执行滚动
        if (targetRef && targetRef.current) {
          targetRef.current.scrollIntoView({
            behavior: 'smooth',
            block: 'center',
            inline: 'center'
          });
        }
      }, 800); // 延迟800ms以确保元素已完全渲染

      return () => clearTimeout(timer);
    }
  }, [isMobile, currentVipLevel]);

  // 会员类型对应的图标映射
  const membershipIconMap: Record<string, string> = {
    'free': freeVip,
    'prelude': ptVip,
    'affinity': xyVip,
    'soulmate': zzVip
  };

  // 根据当前语言获取token单位名称
  const getTokenUnitName = () => {
    return i18n.language.startsWith('ja') ? 'ジェム' : 'tokens';
  };

  // 处理订阅选项点击
  const handlePlanSelect = (planType: string) => {
    // 获取产品的会员类型
    const membershipType = planType.split('_')[0];

    // 检查是否为当前会员等级
    const userCurrentPlan = currentVipLevel ? vipLevelToPlan[currentVipLevel] : undefined;
    const isCurrentPlan = userCurrentPlan === membershipType;

    // 判断是否应该禁用（不属于当前等级的产品）
    // 非会员(currentVipLevel === 0)只能选择free类型的产品
    // 会员只能选择对应等级的产品
    const shouldDisable = currentVipLevel === 0
      ? membershipType !== 'free'  // 非会员只能选择free类型
      : currentVipLevel > 0 && !isCurrentPlan;  // 会员只能选择对应等级

    // 如果产品被禁用，则不允许选择
    if (shouldDisable) {
      return;
    }

    // 如果点击已选中的选项，则取消选择
    if (selectedPlan === planType) {
      setSelectedPlan('');
    } else {
      setSelectedPlan(planType);
    }
  };

  // 处理会员类型点击
  const handleMembershipClick = (membershipType: string) => {
    navigate('/subscriptions', { state: { selectedMembership: membershipType } });
  };

  // 处理支付按钮点击
  const handlePaymentClick = async (event: React.MouseEvent<HTMLButtonElement>) => {
    event.preventDefault(); // 阻止表单提交

    if (!selectedPlan) {
      messageApi.warning(t('tokenModal.errors.selectPlan'));
      return;
    }

    // console.log(t('tokenModal.logs.paymentWithPlan') + ':', selectedPlan);

    // 设置loading状态
    setIsLoading(true);

    try {
      // 获取存储的用户数据
      const userDataString = localStorage.getItem('userData');

      if (!userDataString) {
        messageApi.error(t('tokenModal.errors.loginRequired'));
        setIsLoading(false);
        return;
      }

      // 解析用户数据
      const userData = JSON.parse(userDataString);
      const { visitor_uuid, user_email } = userData;

      if (!visitor_uuid || !user_email) {
        messageApi.error(t('tokenModal.errors.userDataIncomplete'));
        setIsLoading(false);
        return;
      }

      // 获取选中计划的价格配置
      const selectedPriceConfig = PRICE_CONFIG[selectedPlan as keyof typeof PRICE_CONFIG];
      if (!selectedPriceConfig) {
        messageApi.error(t('tokenModal.errors.invalidPlan'));
        setIsLoading(false);
        return;
      }

      // 根据当前语言为计划名称设置正确的单位
      const tokenAmount = selectedPlan.includes('_1000') ? '1000' : '5000';
      const tokenUnit = getTokenUnitName();

      // 构造请求参数
      const requestParams = {
        stripe_price_id: selectedPriceConfig.stripe_price_id,
        user_uuid: visitor_uuid,
        email: user_email
      };

      // console.log('Payment request params:', requestParams);

      const res = await request.post('/api/stripe/create-payment-intent', requestParams);

      if (res.status === 200 && res.data) {
        // console.log('Payment intent created:', res.data);
        // 将支付信息存储到sessionStorage，以便在Pay页面使用
        sessionStorage.setItem('paymentData', JSON.stringify({
          clientSecret: res.data.clientSecret,
          amount: res.data.amount || 0,
          currency: res.data.currency || 'JPY',
          selectedPlan: selectedPlan,
          subscriptionId: res.data.subscriptionId,
          customerId: res.data.customerId,
          order_id: res.data.order_id,
          paymentIntentId: res.data.paymentIntentId,
          invoiceId: res.data.invoiceId,
          message: res.data.message,
          stripe_price_id: selectedPriceConfig.stripe_price_id
        }));

        // 跳转到支付页面
        navigate('/PayMoney');
      } else {
        // console.error('支付请求失败:', res);
        console.error('payment request failed', res);
        messageApi.error(t('tokenModal.errors.paymentFailed'));
        setIsLoading(false);
      }
    } catch (error: any) {
      console.error(t('tokenModal.logs.paymentError') + ':', error.response?.data?.message || t('tokenModal.errors.networkError'));

      // Handle specific error messages with internationalization
      if (error.response?.data?.message === '请先升级会员，才可享受该折扣哦！') {
        messageApi.error(t('tokenModal.errors.membershipRequired'));
      } else {
        messageApi.error(error.response?.data?.message || t('tokenModal.errors.networkError'));
      }

      setIsLoading(false);
    }
  };

  // 渲染会员列
  const renderMembershipColumn = (membershipType: string) => {
    const membership = MEMBERSHIP_TYPES[membershipType];
    const option1000Key = `${membershipType}_1000`;
    const option5000Key = `${membershipType}_5000`;
    const option1000 = PRICE_CONFIG[option1000Key];
    const option5000 = PRICE_CONFIG[option5000Key];

    // 检查是否为当前会员等级
    const userCurrentPlan = currentVipLevel ? vipLevelToPlan[currentVipLevel] : undefined;
    const isCurrentPlan = userCurrentPlan === membershipType;

    // 判断是否应该禁用（不属于当前等级的产品）
    // 非会员(currentVipLevel === 0)只能选择free类型的产品
    // 会员只能选择对应等级的产品
    const shouldDisable = currentVipLevel === 0
      ? membershipType !== 'free'  // 非会员只能选择free类型
      : currentVipLevel > 0 && !isCurrentPlan;  // 会员只能选择对应等级

    return (
      <div className={`flex flex-col ${isMobile ? 'w-[85%] min-w-[250px] h-full' : 'w-full'} px-0.5 md:p-3 ${membership.highlight ? 'relative z-10' : ''} relative ${shouldDisable ? 'opacity-50' : ''}`}>
        {/* 会员类型图标 - 移动端隐藏，md及以上屏幕显示，非会员不显示 */}
        {membershipType !== 'free' && (
          <div
            className={`hidden md:block absolute -top-12 right-0 w-24 h-24 z-20 ${shouldDisable ? 'grayscale' : ''}`}
          >
            <img src={membershipIconMap[membershipType]} alt="" className="w-full h-full object-contain" />
          </div>
        )}

        {/* 当前等级印章 - 参考 subscriptions.tsx */}
        <AnimatePresence>

        </AnimatePresence>

        {/* 最外层的卡片盒子  */}
        <div
          className={`rounded-lg ${membership.highlight && !shouldDisable ? 'gradient-border-card' : ''} ${membershipType === 'affinity' && !shouldDisable ? 'scale-105 -translate-y-1' : ''} transition-all duration-300 ${!shouldDisable ? 'hover:scale-105 hover:-translate-y-1' : ''} ${shouldDisable ? 'grayscale cursor-not-allowed' : ''}`}
        >
          {/* 头部  */}
          <div
            className={`p-2 md:p-4 rounded-t-lg text-center transition-all duration-200 ${shouldDisable
              ? 'bg-gray-600 cursor-not-allowed'
              : membership.highlight
                ? 'bg-gradient-to-r from-[rgb(225,32,78)] to-[rgb(252,118,138)] shadow-lg shadow-[rgb(225,32,78)]/20 relative z-10 cursor-pointer'
                : hoveredCard === `header_${membershipType}` ? 'bg-zinc-700 cursor-pointer' : 'bg-zinc-800 cursor-pointer'
              } ${membership.highlight ? 'relative' : ''}`}
            onClick={shouldDisable ? undefined : () => handleMembershipClick(membershipType)}
            onMouseEnter={shouldDisable ? undefined : () => setHoveredCard(`header_${membershipType}`)}
            onMouseLeave={shouldDisable ? undefined : () => setHoveredCard(null)}
          >
            {/* 标题  */}
            <h3
              style={{ fontFamily: dynamicFonts.font4 }}
              className={`text-sm md:text-lg font-bold ${shouldDisable ? 'text-gray-400' : 'text-white'}`}
            >
              {t(`buyToken.membershipTypes.${membershipType}.name`)}
            </h3>

            {/* 描述/查看详情  */}
            <p
              style={{ fontFamily: dynamicFonts.font3 }}
              className={`text-xs md:text-sm transition-all duration-300 ${shouldDisable
                ? 'text-gray-500'
                : hoveredCard === `header_${membershipType}` ? 'text-white/70' : 'text-gray-200'
                }`}
            >
              {shouldDisable
                ? t(`buyToken.membershipTypes.${membershipType}.description`)
                : hoveredCard === `header_${membershipType}`
                  ? t('buyToken.clickForDetails')
                  : t(`buyToken.membershipTypes.${membershipType}.description`)
              }
            </p>
          </div>

          {/* 1000 tokens 选项 */}
          <div
            className={`p-2 md:p-3 border-l border-r border-zinc-700 transition-colors duration-200 ${shouldDisable
              ? 'bg-gray-800 cursor-not-allowed'
              : selectedPlan === option1000Key
                ? 'bg-zinc-900 cursor-pointer hover:bg-zinc-800 scale-[1.02] shadow-[0_0_10px_rgba(59,130,246,0.3)]'
                : 'bg-zinc-900 cursor-pointer hover:bg-zinc-800'
              }`}
            onClick={shouldDisable ? undefined : () => handlePlanSelect(option1000Key)}
            onMouseEnter={shouldDisable ? undefined : () => setHoveredCard(option1000Key)}
            onMouseLeave={shouldDisable ? undefined : () => setHoveredCard(null)}
          >
            <div
              className={`p-2 md:p-3 rounded-lg transition-all duration-200 ${shouldDisable
                ? 'border border-gray-600 bg-gray-700'
                : selectedPlan === option1000Key
                  ? 'border-2 border-blue-500 bg-blue-900/20'
                  : hoveredCard === option1000Key
                    ? 'border border-gray-500 bg-zinc-800'
                    : 'border border-zinc-700'
                }`}
            >
              <div className="flex justify-between items-center">
                <div className="flex items-center">
                  {/* 添加token图标在左侧 - 1000 tokens使用gem图标 */}
                  <div className="flex-shrink-0 flex items-center justify-center mr-2">
                    <img src={gem} className={`w-4 h-4 xs:w-5 xs:h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 lg:w-7 lg:h-7 object-contain ${shouldDisable ? 'grayscale opacity-50' : ''}`} alt="token" style={{
                      width: '2.5rem',
                      height: "2.5rem",
                      maxWidth: '100%',
                      maxHeight: '100%'
                    }} />
                  </div>
                  {/* 数量 - 根据语言显示不同单位 */}
                  <div>
                    <p
                      style={{ fontFamily: dynamicFonts.font3 }}
                      className={`text-sm md:text-[1.4rem] font-bold ${shouldDisable ? 'text-gray-400' : 'text-white'}`}
                    >
                      {`1,000 ${getTokenUnitName()}`}
                    </p>
                    {/* 介绍  */}
                    {option5000.discount && (
                      // 节省 
                      <p
                        style={{ fontFamily: dynamicFonts.font3 }}
                        className={`text-[10px] md:text-[0.9rem] md:mt-1 ${shouldDisable
                          ? 'text-gray-500'
                          : membership.highlight ? 'text-rose-500' : 'text-rose-300'
                          }`}
                      >
                        {option1000.discount?.replace('节省', '')} {t('buyToken.tokenPackages.jy')}
                      </p>
                    )}
                  </div>
                </div>
                {/* 价格  */}
                <div
                  style={{ fontFamily: `${dynamicFonts.font3}, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif` }}
                  className={`text-base xs:text-lg md:text-[1.3rem] font-bold ${shouldDisable
                    ? 'text-gray-500'
                    : membership.highlight ? 'text-rose-500' : 'text-white'
                    }`}
                >
                  {option1000.price}
                </div>
              </div>
            </div>
          </div>

          {/* 5000 tokens 选项 */}
          <div
            className={`p-2 md:p-3 border-l border-r border-b border-zinc-700 transition-colors duration-200 ${shouldDisable
              ? 'bg-gray-800 cursor-not-allowed'
              : selectedPlan === option5000Key
                ? 'bg-zinc-900 cursor-pointer hover:bg-zinc-800 scale-[1.02] shadow-[0_0_10px_rgba(59,130,246,0.3)]'
                : 'bg-zinc-900 cursor-pointer hover:bg-zinc-800'
              }`}
            onClick={shouldDisable ? undefined : () => handlePlanSelect(option5000Key)}
            onMouseEnter={shouldDisable ? undefined : () => setHoveredCard(option5000Key)}
            onMouseLeave={shouldDisable ? undefined : () => setHoveredCard(null)}
          >
            <div
              className={`p-2 md:p-3 rounded-lg transition-all duration-200 ${shouldDisable
                ? 'border border-gray-600 bg-gray-700'
                : selectedPlan === option5000Key
                  ? 'border-2 border-blue-500 bg-blue-900/20'
                  : hoveredCard === option5000Key
                    ? 'border border-gray-500 bg-zinc-800'
                    : 'border border-zinc-700'
                }`}
            >
              <div className="flex justify-between items-center">
                <div className="flex items-center">
                  {/* 添加token图标在左侧 - 5000 tokens使用Moregem图标 */}
                  <div className="flex-shrink-0 flex items-center justify-center mr-2">
                    <img src={Moregem} className={`w-4 h-4 xs:w-5 xs:h-5 sm:w-6 sm:h-6 md:w-7 md:h-7 lg:w-7 lg:h-7 object-contain ${shouldDisable ? 'grayscale opacity-50' : ''}`} alt="token" style={{
                      width: '2.5rem',
                      height: "2.5rem",
                      maxWidth: '100%',
                      maxHeight: '100%'
                    }} />
                  </div>
                  <div>
                    {/* 根据语言显示不同单位 */}
                    <p
                      style={{ fontFamily: dynamicFonts.font3 }}
                      className={`text-sm md:text-[1.4rem] font-bold ${shouldDisable ? 'text-gray-400' : 'text-white'}`}
                    >
                      {`5,000 ${getTokenUnitName()}`}
                    </p>
                    {option5000.discount && (
                      // 节省 
                      <p
                        style={{ fontFamily: dynamicFonts.font3 }}
                        className={`text-[10px] md:text-[0.9rem] md:mt-1 ${shouldDisable
                          ? 'text-gray-500'
                          : membership.highlight ? 'text-rose-500' : 'text-rose-300'
                          }`}
                      >
                        {option5000.discount.replace('节省', '')} {t('buyToken.tokenPackages.jy')}
                      </p>
                    )}
                    {option5000.recommended && (
                      <p
                        style={{ fontFamily: dynamicFonts.font3 }}
                        className={`text-[10px] md:text-[0.9rem] ${shouldDisable ? 'text-gray-500' : 'text-yellow-400'}`}
                      >
                        {t('buyToken.tokenPackages.recommended')}
                      </p>
                    )}
                  </div>
                </div>
                <div
                  style={{ fontFamily: `${dynamicFonts.font3}, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif` }}
                  className={`text-base xs:text-lg md:text-[1.3rem] font-bold ${shouldDisable
                    ? 'text-gray-500'
                    : membership.highlight ? 'text-rose-500' : 'text-white'
                    }`}
                >
                  {option5000.price}
                </div>
              </div>
            </div>
          </div>
        </div>
        {/* 高亮标签 */}
        {membership.highlight && !shouldDisable && (
          <>
            <div
              style={{ fontFamily: dynamicFonts.font4 }}
              className="absolute top-[-0.75rem] left-0.5 sm:left-1 md:left-2 w-max px-1.5 sm:px-2 md:px-4 py-0.5 sm:py-1 bg-gradient-to-r from-[rgb(225,32,78)] to-[rgb(252,118,138)] text-white text-[10px] sm:text-xs md:text-sm lg:text-base font-bold rounded-full shadow-md shadow-[rgb(225,32,78)]/20 z-20 hover:scale-105 transition-transform duration-200"
            >
              {t('buyToken.popularChoice')}
            </div>
            {/* 添加星星装饰 */}
            <div
              className="absolute -top-2 -left-2 w-2 h-2 sm:w-3 sm:h-3 md:w-4 md:h-4 text-yellow-400 opacity-75"
            >
              ✦
            </div>
            <div
              className="absolute -bottom-2 -right-2 w-2 h-2 sm:w-3 sm:h-3 md:w-4 md:h-4 text-yellow-400 opacity-75"
            >
              ✦
            </div>
          </>
        )}
      </div>
    );
  };

  // 在return前添加自定义动画和媒体查询
  const customStyles = `
  @keyframes bounce-slow {
    0%, 100% {
      transform: translateY(0);
    }
    50% {
      transform: translateY(-10px);
    }
  }
  .animate-bounce-slow {
    animation: bounce-slow 3s ease-in-out infinite;
  }
  
  @keyframes gradient-animation {
    0% {
      background-position: 0% 50%;
    }
    50% {
      background-position: 100% 50%;
    }
    100% {
      background-position: 0% 50%;
    }
  }
  
  .gradient-border-card {
    position: relative;
    border-radius: 0.5rem;
  }
  
  .gradient-border-card::before {
    content: "";
    position: absolute;
    inset: 0;
    padding: 2px;
    border-radius: 0.5rem;
    background: linear-gradient(
      to right,
      rgb(225, 32, 78),
      rgb(252, 118, 138),
      rgb(225, 32, 78)
    );
    background-size: 200% 200%;
    animation: gradient-animation 3s ease infinite;
    -webkit-mask: 
      linear-gradient(#fff 0 0) content-box, 
      linear-gradient(#fff 0 0);
    -webkit-mask-composite: xor;
    mask-composite: exclude;
    pointer-events: none;
    z-index: 10;
  }
  
  .mobile-card-container {
    overflow-x: auto;
    overflow-y: hidden; /* 禁止垂直滚动 */
    -webkit-overflow-scrolling: touch;
    scrollbar-width: none; /* Firefox */
    -ms-overflow-style: none; /* IE and Edge */
    scroll-snap-type: x mandatory;
    padding-bottom: 15px;
    min-height: 16rem; /* 调整容器高度 */
    display: flex;
    align-items: center; /* 垂直居中对齐 */
  }
  
  .mobile-card-container::-webkit-scrollbar {
    display: none; /* Chrome, Safari, Opera */
  }
  
  .mobile-card-item {
    scroll-snap-align: center;
    height: 100%;
    display: flex;
    align-items: center;
  }
  
  /* 自定义断点：屏幕宽度大于等于1626px时显示为一行四列 */
  @media (min-width: 1626px) {
    .membership-grid {
      grid-template-columns: repeat(4, minmax(0, 1fr));
    }
    /* 大屏幕下按照新顺序排列：soulmate, affinity, prelude, free */
    .membership-item.order-1 { order: 1; } /* soulmate */
    .membership-item.order-2 { order: 2; } /* affinity(推荐) */
    .membership-item.order-3 { order: 3; } /* prelude */
    .membership-item.order-4 { order: 4; } /* free */
  }
  
  /* 屏幕宽度小于1626px时减少卡片宽度，保持每行两个元素 */
  @media (max-width: 1625px) {
    .membership-grid {
      grid-template-columns: repeat(auto-fit, minmax(267px, 1fr));
      grid-auto-flow: row;
    }
    /* 确保每行至少有两个元素 */
    .membership-grid > div {
      min-width: calc(50% - 1rem);
      max-width: 100%;
    }
    /* 将推荐产品放在第二个位置 */
    .membership-item.order-1 { order: 1; }
    .membership-item.order-2 { 
      order: 2; /* 推荐产品放在第二个位置 */
      transform: scale(1.02); /* 稍微放大 */
      z-index: 10; /* 确保在最上层 */
    }
    .membership-item.order-3 { order: 3; }
    .membership-item.order-4 { order: 4; }
  }
  
  /* 小屏幕设备保持两列 */
  @media (max-width: 640px) {
    .membership-grid {
      grid-template-columns: repeat(2, minmax(0, 1fr));
      gap: 0.5rem;
    }
    /* 移动设备上也保持推荐产品在第二个位置 */
    .membership-item.order-1 { order: 1; }
    .membership-item.order-2 { order: 2; }
    .membership-item.order-3 { order: 3; }
    .membership-item.order-4 { order: 4; }
  }
  `;

  return (
    <div className={`${isMobile ? 'w-[95vw]' : 'w-[100%] md:w-[90%] xl:w-[88%]'} max-w-full mx-auto relative bg-transparent md:bg-zinc-900 rounded-lg border border-zinc-800 isolate mt-1 md:mt-6 flex flex-col px-2 md:px-4 ${isMobile ? 'py-2' : 'py-4'} ${className}`}>
      {/* 自定义动画样式 */}
      <style dangerouslySetInnerHTML={{ __html: customStyles }} />

      {/* 左下角装饰图 */}
      <div className="absolute bottom-0 left-[-3rem] w-40 h-40 md:w-64 md:h-64  pointer-events-none z-0 overflow-hidden">
        <img src={perion2} alt="" className="w-full h-full object-contain " />
      </div>

      {/* 最大的标题和介绍 */}
      <div className="text-center md:mb-8 relative z-10">
        <h2 style={{ fontFamily: dynamicFonts.font4 }} className="text-xl md:text-3xl font-bold text-white mb-2">{t('buyToken.title')}</h2>
        {/* <p
          style={{ fontFamily: dynamicFonts.font3 }}
          className="hidden md:block text-sm md:text-base text-gray-400 max-w-2xl mx-auto"
        >
          {t('buyToken.subtitle')}
        </p>
        <div
          style={{ fontFamily: dynamicFonts.font3 }}
          className="hidden md:block mt-4 text-xs md:text-sm text-rose-400"
        >
          <Link to="/subscriptions" className="hover:underline">
            {t('buyToken.upgradeTip')} →
          </Link>
        </div> */}
      </div>

      {/* 会员类型和代币选择 - 根据设备类型选择布局 */}
      {isMobile ? (
        // 移动端布局 - 横向滚动布局
        <div className="mobile-card-container flex gap-3 mb-6 md:mb-8 max-w-full">
          <div
            className="mobile-card-item flex-shrink-0"
            ref={soulmateCardRef}
          >
            {renderMembershipColumn('soulmate')}
          </div>
          <div
            className="mobile-card-item flex-shrink-0"
            ref={affinityCardRef}
          >
            {renderMembershipColumn('affinity')}
          </div>
          <div
            className="mobile-card-item flex-shrink-0"
            ref={preludeCardRef}
          >
            {renderMembershipColumn('prelude')}
          </div>
          <div
            className="mobile-card-item flex-shrink-0"
            ref={freeCardRef}
          >
            {renderMembershipColumn('free')}
          </div>
        </div>
      ) : (
        // PC端布局 - 网格布局
        <div className="grid membership-grid gap-2 md:gap-4 mb-8" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(267px, 1fr))' }}>
          <div className="membership-item order-1" ref={soulmateCardRef}>{renderMembershipColumn('soulmate')}</div>
          <div className="membership-item order-2 recommended-item" ref={affinityCardRef}>{renderMembershipColumn('affinity')}</div>
          <div className="membership-item order-3" ref={preludeCardRef}>{renderMembershipColumn('prelude')}</div>
          <div className="membership-item order-4" ref={freeCardRef}>{renderMembershipColumn('free')}</div>
        </div>
      )}

      {/* 选择提示 */}
      {!selectedPlan && (
        <div style={{ fontFamily: dynamicFonts.font3 }} className="text-center text-amber-400 mb-4 animate-pulse text-sm md:text-base">
          {t('buyToken.selectPrompt')}
        </div>
      )}

      {/* 支付按钮 */}
      <div className="max-w-md mx-auto w-full">
        <button
          style={{ fontFamily: dynamicFonts.font3 }}
          className={`w-full px-4 py-4 rounded-lg flex justify-center items-center gap-2 mb-3 transition-all duration-200 ${!selectedPlan || isLoading
            ? 'bg-gray-500 cursor-not-allowed opacity-70'
            : 'bg-gradient-to-r from-rose-600 to-pink-500 shadow-lg hover:shadow-rose-500/30 hover:scale-[1.02] active:scale-[0.98]'
            }`}
          onClick={handlePaymentClick}
          disabled={!selectedPlan || isLoading}
        >
          {isLoading ? (
            <>
              <div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white"></div>
              <div className="text-white text-xs md:text-sm font-medium">
                {t('buyToken.processing')}
              </div>
            </>
          ) : (
            <>
              <div
                style={{ fontFamily: `${dynamicFonts.font3}, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif` }}
                className="text-white text-2xl"
              >
                {PRICE_CONFIG[selectedPlan]?.price}
              </div>
              <div
                className="flex gap-1"
              >
                <img src={visaicon} className="w-[32px] h-5 rounded-[5px]" alt="visa" />
                <img src={wsd} className="w-[32px] h-5 rounded-[5px]" alt="mastercard" />
              </div>
            </>
          )}
        </button>
      </div>

      {/* 安全提示 */}
      <div style={{ fontFamily: dynamicFonts.font4 }} className="mt-6 text-center">
        <div className="flex justify-center items-center gap-2 mb-2">
          <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 text-green-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
          <p className="text-xs md:text-sm text-gray-300">{t('buyToken.securityInfo')}</p>
        </div>
        <p className="text-[10px] md:text-xs text-gray-500">{t('buyToken.termsAgreement')}</p>
      </div>
    </div>
  );
};

export default BuyToken;